package com.xdjk.networkdemo.net;

import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by zhanghs on 2017/8/16.
 * 拦截器工具类!
 */

public class NetInterceptorUtil {

    //日志拦截器
    public static HttpLoggingInterceptor LogInterceptor() {
        /*BODY 内容也就是文件，当打印的内容（也就是文件大小）超过分配的运行内存时，就会报错。*/
//        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS);
    }

    public static Interceptor HeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);
                String cacheControl = request.cacheControl().toString();
                if (TextUtils.isEmpty(cacheControl)) {
                    cacheControl = "public, max-age=60";
                }
                return response.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                        .removeHeader("Pragma")
                        .build();
            }
        };
    }

    public static Interceptor DownloadInterceptor(DownloadCallBack listener) {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());

                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), listener))
                        .build();
            }
        };
    }
}


